<template>
  <div ref="editor" :style="{ width }"></div>
</template>

<script lang="ts" setup>
  import { onBeforeUnmount, onMounted, ref, watchEffect, watch } from 'vue';
  import WangEditor from 'wangeditor';

  const props = defineProps({
    value: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    width: {
      type: [String, Number],
    },
  });
  const emits = defineEmits(['update:value', 'change', 'blur']);
  const editor = ref();
  const isFirst = ref(true);
  const content = ref('');

  watch(content, (val) => {
    emits('update:value', val);
    emits('change');
    instance?.txt.text(props.value || val);
  });

  let instance: WangEditor | null;

  onMounted(() => {
    instance = new WangEditor(editor.value);
    // 菜单栏提示为下标
    instance.config.menuTooltipPosition = 'down';
    Object.assign(instance.config, {
      zIndex: 9,
      onchange: (html: string) => {
        content.value = html;
      },
      onblur: () => {
        if (!isFirst.value) {
          //第一次进入页面不触发blur
          emits('blur');
        }
        isFirst.value = false;
      },
    });
    instance.create();
    instance?.txt.text(props.value || '');
    watchEffect(() => (instance && props.disabled ? instance.disable() : instance?.enable()));
  });

  watch(
    () => props.value,
    (val) => {
      instance?.txt.text(val);
    },
    {
      immediate: true,
    },
  );

  onBeforeUnmount(() => {
    instance && instance.destroy();
    instance = null;
  });
</script>
<style lang="less" scoped>
  :deep(.w-e-text-container) {
    background-color: v-bind("props.disabled ? '#f5f5f5': '#fff'");
  }
</style>
